package com.campusbackend.service.impl;

import com.campusbackend.entity.Teams;
import com.campusbackend.entity.TeamMembers;
import com.campusbackend.entity.vo.TeamDetailVO;
import com.campusbackend.entity.vo.TeamUpdateVO;
import com.campusbackend.entity.vo.TeamListVO;
import com.campusbackend.entity.vo.TeacherTeamsVO;
import com.campusbackend.entity.vo.TeamEditVO;
import com.campusbackend.entity.vo.TeamMembersUpdateVO;
import com.campusbackend.entity.vo.StudentTeamVO;
import com.campusbackend.entity.vo.AdminTeamListVO;
import com.campusbackend.entity.vo.AdminTeamDetailVO;
import com.campusbackend.mapper.TeamsMapper;
import com.campusbackend.mapper.TeamMembersMapper;
import com.campusbackend.service.TeamsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 队伍表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-26
 */
@Service
public class TeamsServiceImpl extends ServiceImpl<TeamsMapper, Teams> implements TeamsService {

    @Autowired
    private TeamsMapper teamsMapper;
    
    @Autowired
    private TeamMembersMapper teamMembersMapper;

    @Override
    public TeamDetailVO getTeamDetail(Long teamId) {
        // 获取队伍基本信息
        Teams team = teamsMapper.selectById(teamId);
        if (team == null) {
            return null;
        }

        // 创建返回对象
        TeamDetailVO teamDetail = new TeamDetailVO();
        BeanUtils.copyProperties(team, teamDetail);
        teamDetail.setTeamId(team.getId());

        // 获取指导老师信息
        TeamDetailVO.InstructorInfo instructor = teamsMapper.getInstructorInfo(team.getInstructorId());
        teamDetail.setInstructor(instructor);

        // 获取队伍成员信息
        List<TeamDetailVO.MemberInfo> members = teamsMapper.getTeamMembers(teamId);
        teamDetail.setMembers(members);

        // 获取入驻专家信息（排除指导老师）
        List<TeamDetailVO.ExpertInfo> experts = teamsMapper.getTeamExperts(teamId, team.getInstructorId());
        teamDetail.setExperts(experts);

        return teamDetail;
    }

    @Override
    public boolean updateTeamInfo(TeamUpdateVO teamUpdateVO) {
        // 参数验证
        if (teamUpdateVO == null || teamUpdateVO.getTeamId() == null) {
            return false;
        }

        // 获取现有队伍信息
        Teams existingTeam = teamsMapper.selectById(teamUpdateVO.getTeamId());
        if (existingTeam == null) {
            return false;
        }

        // 更新队伍信息
        Teams updateTeam = new Teams();
        updateTeam.setId(teamUpdateVO.getTeamId());
        
        // 只更新非空字段
        if (teamUpdateVO.getTeamName() != null) {
            updateTeam.setTeamName(teamUpdateVO.getTeamName());
        }
        if (teamUpdateVO.getTeamIntro() != null) {
            updateTeam.setTeamIntro(teamUpdateVO.getTeamIntro());
        }
        if (teamUpdateVO.getCurrentCompetition() != null) {
            updateTeam.setCurrentCompetition(teamUpdateVO.getCurrentCompetition());
        }
        if (teamUpdateVO.getAwardInfo() != null) {
            updateTeam.setAwardInfo(teamUpdateVO.getAwardInfo());
        }
        
        updateTeam.setUpdateTime(LocalDateTime.now());

        // 执行更新
        int result = teamsMapper.updateById(updateTeam);
        return result > 0;
    }

    @Override
    public TeacherTeamsVO getTeacherTeams(Long teacherId) {
        // 获取教师组建的队伍
        List<TeamListVO> createdTeams = teamsMapper.getTeacherCreatedTeams(teacherId);
        
        // 获取教师入驻的队伍
        List<TeamListVO> expertTeams = teamsMapper.getTeacherExpertTeams(teacherId);
        
        // 构造返回对象
        TeacherTeamsVO teacherTeams = new TeacherTeamsVO();
        teacherTeams.setTeacherId(teacherId);
        
        // 从第一个队伍中获取教师姓名（如果有的话）
        if (!createdTeams.isEmpty()) {
            teacherTeams.setTeacherName(createdTeams.get(0).getInstructorName());
        } else if (!expertTeams.isEmpty()) {
            // 如果没有组建的队伍，尝试从入驻队伍中获取，但需要另外查询
            // 这里可以根据需要优化，暂时设为空
            teacherTeams.setTeacherName("");
        }
        
        teacherTeams.setCreatedTeams(createdTeams);
        teacherTeams.setExpertTeams(expertTeams);
        teacherTeams.setCreatedCount(createdTeams.size());
        teacherTeams.setExpertCount(expertTeams.size());
        
        return teacherTeams;
    }

    @Override
    public List<TeamListVO> getAllTeams(Long currentTeacherId) {
        return teamsMapper.getAllTeams(currentTeacherId);
    }

    @Override
    public TeamEditVO getTeamEditInfo(Long teamId) {
        // 获取队伍基本信息
        Teams team = teamsMapper.selectById(teamId);
        if (team == null) {
            return null;
        }

        // 构造返回对象
        TeamEditVO teamEditVO = new TeamEditVO();
        BeanUtils.copyProperties(team, teamEditVO);
        teamEditVO.setTeamId(team.getId());

        // 获取指导老师信息
        TeamDetailVO.InstructorInfo instructor = teamsMapper.getInstructorInfo(team.getInstructorId());
        if (instructor != null) {
            teamEditVO.setInstructorName(instructor.getRealName());
        }

        // 获取队伍成员编辑信息
        List<TeamEditVO.TeamMemberEditVO> members = teamsMapper.getTeamEditMembers(teamId);
        teamEditVO.setMembers(members);

        return teamEditVO;
    }

    @Override
    @Transactional
    public boolean updateTeamMembers(Long teamId, TeamMembersUpdateVO updateVO) {
        // 参数验证
        if (teamId == null || updateVO == null || updateVO.getMembers() == null) {
            throw new RuntimeException("参数不能为空");
        }

        // 验证队伍是否存在
        Teams team = teamsMapper.selectById(teamId);
        if (team == null) {
            throw new RuntimeException("队伍不存在");
        }

        // 验证队长数量（必须有且只能有一个队长）
        long captainCount = updateVO.getMembers().stream()
                .filter(member -> "队长".equals(member.getMemberRole()))
                .count();
        if (captainCount != 1) {
            throw new RuntimeException("队伍必须有且只能有一个队长");
        }

        try {
            // 1. 删除原有所有成员关系
            QueryWrapper<TeamMembers> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("team_id", teamId);
            teamMembersMapper.delete(deleteWrapper);

            // 2. 创建新的成员关系
            LocalDateTime now = LocalDateTime.now();
            for (TeamMembersUpdateVO.MemberUpdateInfo memberInfo : updateVO.getMembers()) {
                TeamMembers teamMember = new TeamMembers();
                teamMember.setTeamId(teamId);
                teamMember.setStudentId(memberInfo.getStudentId());
                teamMember.setMemberRole(memberInfo.getMemberRole());
                teamMember.setJoinStatus((byte) 1); // 1-已加入
                teamMember.setJoinTime(now);
                teamMember.setCreateTime(now);
                teamMember.setUpdateTime(now);
                
                teamMembersMapper.insert(teamMember);
            }

            // 3. 更新队伍成员数量和类型
            Teams updateTeam = new Teams();
            updateTeam.setId(teamId);
            updateTeam.setCurrentMembers(updateVO.getMembers().size());
            if (updateVO.getTeamType() != null) {
                updateTeam.setTeamType(updateVO.getTeamType());
            }
            updateTeam.setUpdateTime(now);
            
            teamsMapper.updateById(updateTeam);

            return true;
        } catch (Exception e) {
            throw new RuntimeException("更新队伍成员失败: " + e.getMessage());
        }
    }

    @Override
    public List<TeamListVO> searchTeams(String keyword, Long currentTeacherId) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAllTeams(currentTeacherId); // 如果没有关键词，返回所有队伍
        }
        return teamsMapper.searchTeams(keyword.trim(), currentTeacherId);
    }

    @Override
    public StudentTeamVO getStudentTeamInfo(Long studentId) {
        // 获取学生基本信息
        StudentTeamVO studentTeam = teamsMapper.getStudentBasicInfo(studentId);
        if (studentTeam == null) {
            return null;
        }

        // 获取学生所属的队伍信息
        StudentTeamVO.TeamInfo teamInfo = teamsMapper.getStudentTeamInfo(studentId);
        if (teamInfo == null) {
            // 学生没有加入任何队伍
            return studentTeam;
        }

        // 获取指导老师信息
        StudentTeamVO.InstructorInfo instructor = teamsMapper.getInstructorInfoForStudent(teamInfo.getInstructorId());
        teamInfo.setInstructor(instructor);

        // 获取队伍成员信息
        List<StudentTeamVO.MemberInfo> members = teamsMapper.getTeamMembersForStudent(teamInfo.getTeamId());
        teamInfo.setMembers(members);

        // 获取入驻专家信息（排除指导老师）
        List<StudentTeamVO.ExpertInfo> experts = teamsMapper.getTeamExpertsForStudent(teamInfo.getTeamId(), teamInfo.getInstructorId());
        teamInfo.setExperts(experts);

        // 设置队伍信息到学生对象中
        studentTeam.setTeamInfo(teamInfo);

        return studentTeam;
    }

    /* ========== 管理端方法实现 ========== */

    @Override
    public List<AdminTeamListVO> getAdminTeamList() {
        return teamsMapper.getAdminTeamList();
    }

    @Override
    public AdminTeamDetailVO getAdminTeamDetail(Long teamId) {
        // 获取队伍基本信息
        Teams team = teamsMapper.selectById(teamId);
        if (team == null) {
            return null;
        }

        // 创建返回对象
        AdminTeamDetailVO teamDetail = new AdminTeamDetailVO();
        BeanUtils.copyProperties(team, teamDetail);
        teamDetail.setTeamId(team.getId());

        // 获取指导老师信息
        AdminTeamDetailVO.InstructorInfo instructor = teamsMapper.getAdminInstructorInfo(team.getInstructorId());
        teamDetail.setInstructor(instructor);

        // 获取队伍成员信息
        List<AdminTeamDetailVO.MemberInfo> members = teamsMapper.getAdminTeamMembers(teamId);
        teamDetail.setMembers(members);

        // 获取入驻专家信息（排除指导老师）
        List<AdminTeamDetailVO.ExpertInfo> experts = teamsMapper.getAdminTeamExperts(teamId, team.getInstructorId());
        teamDetail.setExperts(experts);

        return teamDetail;
    }

    @Override
    public List<AdminTeamListVO> adminSearchTeams(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAdminTeamList();
        }
        return teamsMapper.adminSearchTeams(keyword.trim());
    }
}
